package dr.joketalker.dao.json;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import dr.joketalker.Debug.MyDebug;
import dr.joketalker.dao.GenericDAO;
import dr.joketalker.entity.Entity;

public abstract class JSONGeneric<T extends Entity> implements GenericDAO<T>{

	
	protected static final String host = "http://joketalker.net78.net/database";

    protected static final String TAG_SUCCESS = "success";
    
    public static final String TABLE 	= "TABLE";
    public static final String COLUMN 	= "COLUMN";
    public static final String ALL 		= "ALL";
    public static final String VALUE 	= "VALUE";
    public static final String ID 		= "ID";
    public static final String CID 		= "CID";
    
    public String TABLENAME;


    protected String tableName = "empty";


protected boolean debug = false;

@Override
public boolean isDebug() {
	// TODO Auto-generated method stub
	return debug;
}
@Override
public void setDebug(boolean a) {
	debug = a;
}

MyDebug myDebug = new MyDebug(this.getClass().getSimpleName());

	
    public List<NameValuePair> getListParams(T entity){
    	List<NameValuePair> listParams = new ArrayList<NameValuePair>();
    	listParams.add(new BasicNameValuePair(TABLE, getTableName()));
    	listParams.add(new BasicNameValuePair(ID,entity.getId()+""));
    	//myDebug.v("table:::: " + getTableName());
    	return listParams;
	}

    @Override
	public Long create(T o){
    	
    	String url = host+ "/insert.php";
    	JSONParser jParser = new JSONParser(); 	
    	
    	//id not necassary
    	List<NameValuePair> listParams =  getListParams(o);
    	listParams.remove(1);
    	
    	JSONObject json = jParser.makeHttpRequest(url,"POST", listParams);

        // check log cat fro response
      //  myDebug.v(json.toString());

        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully created product
            	return new Long(json.getInt(ID));
            
            } else {
               return null;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public abstract T buildEntityFromJson(JSONObject jsonO);
	
    


    @Override
    public T read(long id) {
    	
    	String url = host+ "/get.php";

    	JSONParser jParser = new JSONParser(); 	
    	 List<NameValuePair> params = new ArrayList<NameValuePair>();
         // getting JSON string from URL
    	 params.add(new BasicNameValuePair(TABLE, getTableName()));
         params.add(new BasicNameValuePair(COLUMN, ID));
         params.add(new BasicNameValuePair(VALUE, (new Long(id)).toString()));
      	params.add(new BasicNameValuePair(CID, String.valueOf(0)));
    	 
         JSONObject json = jParser.makeHttpRequest(url, "GET", params);
         
         // Check your log cat for JSON reponse
        
         try {
        	// myDebug.v(json.toString());
             // Checking for SUCCESS TAG
             int success = json.getInt(TAG_SUCCESS);

             if (success == 1) {

                 JSONArray jsonArray = json.getJSONArray(getTableName());


                     JSONObject c = jsonArray.getJSONObject(0);
                     T entity = buildEntityFromJson(c);
                     //myDebug.v(entity.toString());

                     return entity;
                 
             } else {

             }
         } catch (JSONException e) {
             e.printStackTrace();
         }

         return null;
    }
    
    
    @Override
    public List<T> readAll(long cid) {
    	
    	List<T> listEntity = new LinkedList<T>();
    	
    	String url = host+ "/get.php";
    	JSONParser jParser = new JSONParser();    	
    	List<NameValuePair> params = new ArrayList<NameValuePair>();
         // getting JSON string from URL
    	params.add(new BasicNameValuePair(TABLE, getTableName()));
    	params.add(new BasicNameValuePair(COLUMN, ALL));
    	params.add(new BasicNameValuePair(CID, String.valueOf(cid)));
    	
    	
         JSONObject json = jParser.makeHttpRequest(url, "GET", params);

         try {
        	 //myDebug.v(json.toString());
             // Checking for SUCCESS TAG
             int success = json.getInt(TAG_SUCCESS);

             if (success == 1) {


                 JSONArray jsonArray = json.getJSONArray(getTableName());

                
                 
                 for(int i = 0; i < jsonArray.length(); i++){
                     JSONObject c = jsonArray.getJSONObject(i);
                     T entity = buildEntityFromJson(c);                     
                     listEntity.add(entity);
                    
                     //myDebug.v(entity.toString());
                 }
                     return listEntity;
                 
             } else {

             }
         } catch (JSONException e) {
             e.printStackTrace();
         }
         return listEntity;
    }
    



    @Override
	public List<T> readAllWhere(String column, String value,long cid){
    	List<T> listEntity = new LinkedList<T>();
    	
    	
    	String url = host+ "/get.php";
    	JSONParser jParser = new JSONParser();    	
    	List<NameValuePair> params = new ArrayList<NameValuePair>();
         // getting JSON string from URL
    	params.add(new BasicNameValuePair(TABLE, getTableName()));
    	params.add(new BasicNameValuePair(COLUMN, column));
    	params.add(new BasicNameValuePair(VALUE, value));
     	params.add(new BasicNameValuePair(CID, String.valueOf(cid)));
 
    	if(isDebug()){
    		params.add(new BasicNameValuePair("DEBUG","1"));
    	}
    	
    	
        JSONObject json = jParser.makeHttpRequest(url, "GET", params);
        myDebug.v(json.toString());
    	
        try {
       	 //myDebug.v(json.toString());
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {

                JSONArray jsonArray = json.getJSONArray(getTableName());

                
                
                for(int i = 0; i < jsonArray.length(); i++){
                    JSONObject c = jsonArray.getJSONObject(i);
                    T entity = buildEntityFromJson(c);                     
                    listEntity.add(entity);
                   
              //      myDebug.v(entity.toString());
                }
                    return listEntity;
                
            } else {

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return listEntity;
    }
    
    @Override
	public void update(T o) {
    	String url = host+ "/update.php";
    	JSONParser jParser = new JSONParser(); 	
    	
    	JSONObject json = jParser.makeHttpRequest(url,"POST", getListParams(o));

        // check log cat fro response
       // myDebug.v(json.toString());

        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully created product
            	
            
            } else {
            
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
       
     }

     @Override
	public void delete(T o) {
         //getSession().delete(o);
     }

	public  String getTableName(){
		return TABLENAME;
	}



	public abstract T getEntityInstance();

}
